package ustc.xiaoyang.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Service;
import ustc.xiaoyang.exception.ClazzHasStudentException;
import ustc.xiaoyang.mapper.ClazzMapper;
import ustc.xiaoyang.mapper.StudentMapper;
import ustc.xiaoyang.pojo.Clazz;
import ustc.xiaoyang.pojo.PageResult;
import ustc.xiaoyang.pojo.dto.ClazzPageQueryDTO;
import ustc.xiaoyang.service.ClazzService;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {

    private final ClazzMapper clazzMapper;
    private final StudentMapper studentMapper;
    public ClazzServiceImpl(ClazzMapper clazzMapper, StudentMapper studentMapper) {
        this.clazzMapper = clazzMapper;
        this.studentMapper = studentMapper;
    }
    @Override
    public PageResult<Clazz> pageList(ClazzPageQueryDTO clazzPageQueryDTO) {
        PageHelper.startPage(clazzPageQueryDTO.getPage(), clazzPageQueryDTO.getPageSize());
        List<Clazz> clazzList = clazzMapper.pageList(clazzPageQueryDTO);
        Page<Clazz> p = (Page<Clazz>) clazzList;
        return new PageResult<>(p.getTotal(), p.getResult());
    }

    @Override
    public void add(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.add(clazz);
    }

    @Override
    public Clazz getById(Integer id) {
        return clazzMapper.getById(id);
    }

    @Override
    public void update(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.update(clazz);
    }

    @Override
    public void deleteById(Integer id) {
        if(studentMapper.countByClazzId(id) > 0){
            throw new ClazzHasStudentException("该班级下有学生，不能删除");
        }
        clazzMapper.deleteById(id);
    }

    @Override
    public List<Clazz> list() {
        return clazzMapper.list();
    }
}
